import React from "react";
import {
  useReactTable,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  flexRender,
} from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableHeader,
  TableRow,
  TableCell,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";

// 假设的数据类型
interface SelectableTableProps {
  columns: any[];
  data: any[];
  selection?: Record<string, boolean>;
  onSelection?: (newSelection: Record<string, boolean>) => void;
}

const SelectableTable: React.FC<SelectableTableProps> = ({
  columns,
  data,
  selection = {},
  onSelection,
}) => {
  const [selectedRowData, setSelectedRowData] = React.useState<null>(null);

  const table = useReactTable({
    data,
    columns,
    state: {
      rowSelection: selection,
    },
    // onStateChange: (state) => {
    //   console.log(state);
    //   console.log(state.rowSelection);
    //   if ("rowSelection" in state && onSelection) {
    //     console.log(state.rowSelection);
    //     onSelection(state.rowSelection);
    //   }
    // },
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    enableRowSelection: true,
  });

  React.useEffect(() => {
    if (Object.keys(table.getState().rowSelection).length > 0) {
      const firstSelectedRow = data.find(
        (row) => table.getState().rowSelection[`${row.id}`]
      );
      setSelectedRowData(firstSelectedRow || null);
    } else {
      setSelectedRowData(null);
    }
  }, [table.getState().rowSelection]);

  return (
    <div className="p-4">
      <div className="w-full">
        <Table>
          <TableHeader>
            <TableRow>
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id}>
                  {headerGroup.headers.map((header) => (
                    <TableCell key={header.id}>
                      {flexRender(
                        header.column.columnDef.header,
                        header.getContext()
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows.map((row) => (
              <TableRow
                key={row.id}
                data-state={row.getIsSelected() && "selected"}
              >
                {row.getVisibleCells().map((cell) => (
                  <TableCell key={cell.id}>
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
      <Button onClick={() => console.log("Selected Row:", selectedRowData)}>
        Submit
      </Button>
    </div>
  );
};

export default SelectableTable;
